package com.gopay.common.rcs.utils;

import com.gopay.common.constants.proccode.ProcCodeEnum;
import com.gopay.common.exception.GopayException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

public class RcsUtil {
    protected final static Log logger = LogFactory.getLog(RcsUtil.class);

    /**
     * 从网址中获取域名/IP，如从http://www.abc.com/query?x=123中获取www.abc.com
     * 
     * @throws GopayException
     */
    public static String getDomainFromReferer(String referer) throws GopayException {
        String host = "";
        if (StringUtils.isEmpty(referer)) {
            return host;
        }
        try {
            String url = referer;
            // 如果URL带参，则首先去参
            if (StringUtils.isNotEmpty(url)) {
                int index = url.indexOf("?");
                if (index > -1) {
                    url = url.substring(0, index);
                }
            }
            host = new URI(url).getHost();
        } catch (URISyntaxException e) {
            logger.info("AntiPhishing-反钓鱼-域名校验失败-报文请求中的Referer格式错误！！！Referer:" + referer);
            throw new GopayException(ProcCodeEnum.PROC_CODE_200E1006);
        }
        return host;
    }

    /**
     * @return 域名模糊匹配-判断域名（name）是否和规则（fuzzy）相匹配。
     */
    public static boolean isDomainnameFuzzyMatch(String name, String fuzzy) {
        try {
            // 把操作员配置的模糊域名转换成正则表达式，比如把“*.google.com”转换成“.*\.google\.com”
            fuzzy = fuzzy.replace("*.", "(*.)?");
            String s = fuzzy.replaceAll("\\.", "\\\\.").replaceAll("\\*", "\\.*");
            boolean r = Pattern.matches(s, name);
            return r;
        } catch (Exception e) {
            logger.warn("AntiPhishingProcess-反钓鱼-域名模糊匹配时发生错误！！name=" + name + "; fuzzy=" + fuzzy + "; " + e);
            return false;
        }
    }
}
